package com.kordar.admin.kernel.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.init.ScriptUtils;

import javax.sql.DataSource;


public class SchemaHandler {
    private final String SCHEMA_SQL = "classpath:schema.sql";
    private final DataSource datasource;
    private final SpringContextGetter springContextGetter;

    public SchemaHandler(DataSource datasource, SpringContextGetter springContextGetter) {
        this.datasource = datasource;
        this.springContextGetter = springContextGetter;
    }

    public void execute() throws Exception {



        Resource resource = springContextGetter.getApplicationContext().getResource(SCHEMA_SQL);

        ScriptUtils.executeSqlScript(datasource.getConnection(), resource);
    }
}

// 获取 ApplicationContext

class SpringContextGetter implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}